package com.sanctuary.products;

import java.io.OutputStream;
import java.io.Writer;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sanctuary.interfaces.Product;
import com.sanctuary.interfaces.TemplateEngine;

public abstract class BaseProduct implements Product {
	private static final Log LOG = LogFactory.getLog(BaseProduct.class);
	
	public abstract String getContentType();

	public abstract void print();

	public void setCompleted(String completed, HttpServletRequest request,
			HttpServletResponse response, TemplateEngine templateEngine,
			Map<String, Object> content) throws Exception {
		String command = completed.split("\\:",2)[0];
		String arg = completed.split("\\:",2)[1];
		
		if ("template".equalsIgnoreCase(command)) {
			Writer w = templateEngine.getContent(arg,content);
			setOutput(w);
		} else if ("binary".equalsIgnoreCase(command)) {
			setOutput(content);	
		} else if ("redirect".equalsIgnoreCase(command)) {
			if (arg.startsWith("$ref")) {
				response.sendRedirect(request.getHeader("Referer"));
			} else if (arg.startsWith("http")) {
				LOG.info("Http redirect: " + arg);
				response.sendRedirect(arg);
			} else {
				response.sendRedirect(getUri(arg,content));
			}
		} else if ("dispatch".equalsIgnoreCase(command)) {
			RequestDispatcher d = request.getRequestDispatcher(getUri(arg,content));
			d.forward(request, response);
		} else if ("class".equalsIgnoreCase(command)) {
			
		} else {
			throw new Exception ("Command: " + command + " was not understood");
		}

	}

	public abstract void setContentType(String ct);
	public abstract void setOutput(Object output);
	public abstract void setOutputStream(OutputStream outputStream);
	public abstract void setWriter(Writer writer);

	public static String getUri(String baseUri, 
			Map<String, Object> content) 
	{
		StringBuffer qs = new StringBuffer();
		String fullUri = "";
		
		if (content != null && content.size() > 0) {
			for (String key : content.keySet()) {
				if (qs.length() == 0) {
					qs.append("?");
				}
				qs.append(key);
				qs.append("=");
				qs.append(content.get(key));
				qs.append("&");
			}
		}

		if (qs.length() > 0) {
			fullUri = baseUri + qs.toString();
		} else {
			fullUri = baseUri;
		}
		return fullUri;
	}

}
